

const http = require('http');
const path = require('path');
const url = require('url');
// const fsp = require('fs/promises');
const fs = require('fs');
const fsp = fs.promises;

const { createServer } = http;

// var server = createServer(function (req,res) { });
var server = createServer();

var siteUrl = path.join(__dirname, "../site"); // 默认站点路径 (前端相关的文件 放到site目录中)


server.on("request", function (req, res) {
    if (req.url != "/favicon.ico") {
        console.log("接收前端发送的请求");
        console.log(req.url);

        var urlInfo = url.parse(req.url, true);
        // console.log(urlInfo);

        var { pathname, query } = urlInfo;


        // 判断 req.url(路径) 在站点中是否存在
        var readPath = path.join(siteUrl, pathname);
        if (fs.existsSync(readPath)) {

            // 如果在站点中存在 -> 取的改文件 -> 传递给前端

            // HTML css JS(!!)
            fsp.readFile(readPath, "utf-8").then(txt => {
                // res.writeHead(200, {
                //     "Content-Type": "image/png",
                // })
                res.end(txt, "utf-8");
            })

            fsp.readFile(readPath, "binary").then(txt => {
                // res.writeHead(200, {
                //     "Content-Type": "image/png",
                // })
                console.log(txt);
                res.end(txt, "binary");
            })
        } else {
            res.end("2222");
        }




    } else {
        res.end();
    }
})


server.listen(3000, function () {
    console.log("服务器启动成功localhost:3000");
})

